/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
var addTwoNumbers = function (l1, l2) {
  let l3 = new ListNode(), carry = 0
  let r = l3
  while (l1 || l2) {

    let temp = new ListNode()
    temp.val = (carry + l1.val + l2.val) % 10
    carry = (carry + l1.val + l2.val) / 10
    l1 = l1.next
    l2 = l2.next
    r.next = temp
    r = r.next
  }

  while (l1) {

    l1.val = (carry + l1.val) % 10
    carry = (carry + l1.val) / 10
    r.next = l1
    l1 = l1.next
  }
  while (l2) {
    l2.val = (carry + l2.val) % 10
    carry = (carry + l2.val) / 10
    r.next = l2
    l2 = l2.next
  }

  return l3
}
